<template>
  <div class="student-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>学生管理</h2>
      <p>管理学生信息，查看提交记录</p>
    </div>

    <!-- 学生数据表格 -->
    <el-card class="table-card" shadow="hover">
      <!-- 表格头部操作区 -->
      <div class="table-header">
        <div class="header-left">
          <h3 class="table-title">学生列表</h3>
        </div>
        <div class="header-right">
          <div class="toolbar-buttons">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加学生
            </el-button>
            <el-button @click="showImportDialog">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button @click="exportStudents">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </div>

      <DataTable
        :data="studentData"
        :columns="studentColumns"
        :loading="loading"
        :pagination="pagination"
        :show-selection="true"
        :show-batch-actions="true"
        :show-index="false"
        :actions="studentActions"
        :filters="filters"
        :draggable="false"
        :search-keyword="searchKeyword"
        height="480"
        @update:search-keyword="searchKeyword = $event"
        @refresh="loadStudents"
        @search="handleSearch"
        @filter-change="handleFilterChange"
        @selection-change="handleSelectionChange"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
        @action="handleStudentAction"
        @batch-delete="handleBatchDelete"
      />
    </el-card>

    <!-- 统计分析图表区域 -->
    <el-row :gutter="24" class="charts-section">
      <el-col :lg="12" :md="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#409EFF">
                <TrendCharts />
              </el-icon>
              <span>专业分布</span>
            </div>
          </template>
          <div ref="majorChartRef" class="chart-container">
            <div class="chart-placeholder">
              <el-icon size="64" color="#C0C4CC">
                <PieChart />
              </el-icon>
              <p>专业分布统计图表</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :lg="12" :md="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#67C23A">
                <Histogram />
              </el-icon>
              <span>班级提交统计</span>
            </div>
          </template>
          <div ref="classChartRef" class="chart-container">
            <div class="chart-placeholder">
              <el-icon size="64" color="#C0C4CC">
                <Histogram />
              </el-icon>
              <p>班级提交次数统计图表</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24" class="charts-section">
      <el-col :lg="12" :md="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#E6A23C">
                <DataLine />
              </el-icon>
              <span>学生注册趋势</span>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container">
            <div class="chart-placeholder">
              <el-icon size="64" color="#C0C4CC">
                <DataLine />
              </el-icon>
              <p>学生注册时间趋势图</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :lg="12" :md="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#F56C6C">
                <DataAnalysis />
              </el-icon>
              <span>活跃度分析</span>
            </div>
          </template>
          <div ref="activityChartRef" class="chart-container">
            <div class="chart-placeholder">
              <el-icon size="64" color="#C0C4CC">
                <DataAnalysis />
              </el-icon>
              <p>学生活跃度分布图</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="editingStudent ? '编辑学生' : '添加学生'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="studentRules"
        label-width="80px"
      >
        <el-form-item label="学号" prop="account">
          <el-input
            v-model="studentForm.account"
            placeholder="请输入9位学号"
            :disabled="!!editingStudent"
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入学生姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        
        <el-form-item label="专业" prop="major">
          <el-select v-model="studentForm.major" placeholder="请选择专业" style="width: 100%">
            <el-option
              v-for="major in majorOptions"
              :key="major"
              :label="major"
              :value="major"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="班级" prop="className">
          <el-select v-model="studentForm.className" placeholder="请选择班级" style="width: 100%" filterable allow-create>
            <el-option
              v-for="className in classNameOptions"
              :key="className"
              :label="className"
              :value="className"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="!editingStudent" label="初始密码" prop="password">
          <el-input
            v-model="studentForm.password"
            type="password"
            placeholder="默认为123456"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitStudent">
          {{ editingStudent ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog 
      v-model="importDialogVisible" 
      title="批量导入学生" 
      width="800px"
      @close="handleImportDialogClose"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          show-icon
        >
          <p>请按照模板格式准备Excel文件，包含学号、姓名、专业、班级、邮箱等信息</p>
        </el-alert>
        
        <div class="import-actions">
          <el-button @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载模板
          </el-button>
        </div>

        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :limit="1"
          :accept="'.xlsx,.xls,.csv'"
          :on-change="handleFileChange"
          :file-list="fileList"
          drag
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 .xlsx、.xls、.csv 格式，单次最多上传1个文件
            </div>
          </template>
        </el-upload>
        
        <!-- 导入预览 -->
        <div v-if="importPreviewData.length > 0" class="import-preview">
          <h4>导入预览（前5条）</h4>
          <el-table :data="importPreviewData" border style="width: 100%">
            <el-table-column prop="account" label="学号" width="120" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="major" label="专业" width="140" />
            <el-table-column prop="className" label="班级" width="120" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="importing" @click="confirmImport">
          开始导入
        </el-button>
      </template>
    </el-dialog>

    <!-- 学生详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      title="学生详情"
      direction="rtl"
      size="50%"
    >
      <div v-if="selectedStudent" class="student-detail">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="学号">{{ selectedStudent.account }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedStudent.name }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ selectedStudent.email }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ selectedStudent.major }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ selectedStudent.className }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="(selectedStudent.status === 'active' || selectedStudent.status === 1) ? 'success' : 'danger'">
              {{ (typeof selectedStudent.status === 'number' ? (selectedStudent.status === 1 ? '正常' : '禁用') : (selectedStudent.status === 'active' ? '正常' : '禁用')) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDateTime(selectedStudent.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatDateTime(selectedStudent.lastLoginTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 提交统计 -->
        <div class="submission-stats">
          <h3>提交统计</h3>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-statistic title="总提交次数" :value="selectedStudent.submissionCount || 0" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="最近提交" :value="getDaysAgo(selectedStudent.lastSubmissionTime)" suffix="天前" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="平均相似度" :value="25.6" suffix="%" />
            </el-col>
          </el-row>
        </div>

        <!-- 最近提交记录 -->
        <div class="recent-submissions">
          <h3>最近提交记录</h3>
          <el-table :data="studentSubmissions" style="width: 100%">
            <el-table-column prop="fileName" label="文件名" />
            <el-table-column prop="similarity" label="相似度" width="100">
              <template #default="scope">
                {{ scope.row.similarity }}%
              </template>
            </el-table-column>
            <el-table-column prop="submitTime" label="提交时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.submitTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import {
  Plus,
  Upload,
  Download,
  Search,
  Edit,
  View,
  Delete,
  TrendCharts,
  PieChart,
  Histogram,
  DataLine,
  DataAnalysis
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/stores/app'
import {
  getStudentList,
  addStudent,
  updateStudent,
  deleteStudent,
  batchDeleteStudents,
  batchImportStudents,
  getOverviewStatistics,
  getTrendStatistics,
  getStudentActivity
} from '@/api/teacher'
import request from '@/utils/request'
import { formatDateTime } from '@/utils'
import DataTable from '@/components/DataTable.vue'
import FileUpload from '@/components/FileUpload.vue'

const appStore = useAppStore()

// 学生表格数据
const studentData = ref([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索和筛选
const searchKeyword = ref('')
const filterForm = ref({})
const filters = [
  {
    prop: 'major',
    label: '专业',
    type: 'select',
    width: '180px',
    options: [
      { value: '计算机科学与技术', label: '计算机科学与技术' },
      { value: '软件工程', label: '软件工程' },
      { value: '网络工程', label: '网络工程' },
      { value: '数据科学与大数据技术', label: '数据科学与大数据技术' },
      { value: '人工智能', label: '人工智能' }
    ]
  },
  {
    prop: 'className',
    label: '班级',
    type: 'select',
    width: '180px',
    options: [
      { value: '软件2416班', label: '软件2416班' },
      { value: '计科2021-1班', label: '计科2021-1班' },
      { value: '计科2021-2班', label: '计科2021-2班' },
      { value: '网络2021-1班', label: '网络2021-1班' },
      { value: '网络2021-2班', label: '网络2021-2班' },
      { value: '数据2021-1班', label: '数据2021-1班' }
    ]
  },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    width: '180px',
    options: [
      { value: 1, label: '正常' },
      { value: 0, label: '禁用' }
    ]
  }
]

// 表格列配置
const studentColumns = [
  {
    prop: 'account',
    label: '学号',
    width: 120,
    fixed: 'left'
  },
  {
    prop: 'name',
    label: '姓名',
    width: 100,
    fixed: 'left'
  },
  {
    prop: 'email',
    label: '邮箱',
    minWidth: 200,
    showOverflowTooltip: true,
    fixed: 'left'
  },
  {
    prop: 'major',
    label: '专业',
    width: 160,
    fixed: 'left'
  },
  {
    prop: 'className',
    label: '班级',
    width: 140,
    fixed: 'left'
  },
  {
    prop: 'submissionCount',
    label: '提交次数',
    width: 100,
    align: 'center',
    fixed: 'left'
  },
  {
    prop: 'lastSubmissionTime',
    label: '最近提交',
    width: 140,
    formatter: (value) => value ? formatDateTime(value, 'MM-DD HH:mm') : '-',
    fixed: 'left'
  },
  // 添加状态列
  {
    prop: 'status',
    label: '状态',
    width: 80,
    formatter: (value) => {
      // 后端返回的是数字，1表示启用(正常)，0表示禁用
      if (typeof value === 'number') {
        return value === 1 ? '正常' : '禁用';
      }
      // 兼容字符串格式
      return value === 'active' ? '正常' : '禁用';
    },
    fixed: 'right'
  }
  // 移除状态和注册时间列
]

// 操作按钮
const studentActions = [
  { key: 'view', label: '查看', type: 'primary', icon: View, size: 'small', title: '查看' },
  { key: 'edit', label: '编辑', type: 'primary', icon: Edit, size: 'small', title: '编辑' },
  { key: 'delete', label: '删除', type: 'danger', icon: Delete, size: 'small', title: '删除' }
]

// 对话框状态
const addDialogVisible = ref(false)
const importDialogVisible = ref(false)
const detailDrawerVisible = ref(false)

// 表单数据
const studentFormRef = ref()
const studentForm = reactive({
  account: '',
  name: '',
  email: '',
  major: '',
  className: '',
  password: '123456'
})

const editingStudent = ref(null)
const submitting = ref(false)

// 专业选项
const majorOptions = [
  '计算机科学与技术',
  '软件工程',
  '网络工程',
  '数据科学与大数据技术',
  '人工智能'
]

// 班级选项
const classNameOptions = [
  '软件2416班',
  '计科2021-1班',
  '计科2021-2班',
  '网络2021-1班',
  '网络2021-2班',
  '数据2021-1班'
]

// 表单验证规则
const studentRules = {
  account: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{9}$/, message: '学号格式不正确（应为9位数字）', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ]
}

// 导入相关
const importFiles = ref([])
const importing = ref(false)
const fileList = ref([])
const importPreviewData = ref([])
const uploadRef = ref()

// 学生详情
const selectedStudent = ref(null)
const studentSubmissions = ref([])
const selectedRows = ref([])

// 图表引用
const majorChartRef = ref()
const classChartRef = ref()
const trendChartRef = ref()
const activityChartRef = ref()

// 加载学生列表
const loadStudents = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current,
      size: pagination.size,
      keyword: searchKeyword.value
    }
    
    // 合并筛选条件
    Object.assign(params, filterForm.value)
    
    console.log('请求学生列表参数:', params)
    const result = await getStudentList(params)
    console.log('获取到的学生数据:', result)
    
    // 支持多种数据结构
    const data = result.data || result
    studentData.value = data.records || []
    pagination.total = data.total || 0
    
    console.log('解析后的数据:', { records: studentData.value.length, total: pagination.total })
    
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadStudents()
}

// 筛选变化
const handleFilterChange = (filters) => {
  console.log('筛选条件变化:', filters)
  filterForm.value = filters
  pagination.current = 1
  loadStudents()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page
  loadStudents()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadStudents()
}

// 学生操作
const handleStudentAction = (actionKey, row) => {
  switch (actionKey) {
    case 'view':
      viewStudent(row)
      break
    case 'edit':
      editStudent(row)
      break
    case 'delete':
      deleteStudentItem(row)
      break
  }
}

// 查看学生详情
const viewStudent = async (student) => {
  selectedStudent.value = student
  // 加载学生提交记录
  studentSubmissions.value = []
  detailDrawerVisible.value = true
}

// 显示添加对话框
const showAddDialog = () => {
  editingStudent.value = null
  addDialogVisible.value = true
}

// 编辑学生
const editStudent = (student) => {
  editingStudent.value = student
  Object.assign(studentForm, student)
  addDialogVisible.value = true
}

// 删除学生
const deleteStudentItem = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生"${student.name}"吗？`,
      '删除确认',
      { type: 'warning' }
    )
    
    console.log('开始删除学生:', student.id)
    const result = await deleteStudent(student.id)
    console.log('删除学生结果:', result)
    
    // 检查删除结果
    if (result && (result.code === 200 || result.success || !result.code)) {
      ElMessage.success('删除成功')
      await loadStudents()
    } else {
      ElMessage.error('删除失败: ' + (result?.message || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除失败: ' + (error.message || error))
    }
  }
}

// 批量删除
const handleBatchDelete = async (students) => {
  try {
    const studentIds = students.map(s => s.id)
    await batchDeleteStudents({ studentIds })
    ElMessage.success('批量删除成功')
    await loadStudents()
  } catch (error) {
    console.error('批量删除失败:', error)
  }
}

// 提交学生表单
const submitStudent = async () => {
  if (!studentFormRef.value) return
  
  try {
    await studentFormRef.value.validate()
    submitting.value = true
    
    if (editingStudent.value) {
      await updateStudent(editingStudent.value.id, studentForm)
      ElMessage.success('更新成功')
    } else {
      await addStudent(studentForm)
      ElMessage.success('添加成功')
    }
    
    addDialogVisible.value = false
    await loadStudents()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (studentFormRef.value) {
    studentFormRef.value.resetFields()
  }
  Object.assign(studentForm, {
    account: '',
    name: '',
    email: '',
    major: '',
    className: '',
    password: '123456'
  })
}

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
  fileList.value = []
  importPreviewData.value = []
}

// 关闭导入对话框
const handleImportDialogClose = () => {
  fileList.value = []
  importPreviewData.value = []
}

// 下载模板
const downloadTemplate = () => {
  // 创建CSV模板内容
  const csvContent = '学号,姓名,邮箱,专业,班级\n241305476,示例学生,example@qq.com,软件工程,软件2416班'
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '学生信息导入模板.csv'
  link.click()
  URL.revokeObjectURL(link.href)
}

// 文件选择处理
const handleFileChange = (file, uploadFileList) => {
  // 保持只有一个文件
  if (uploadFileList.length > 1) {
    uploadFileList.splice(0, 1)
  }
  
  // 更新fileList
  fileList.value = uploadFileList
  
  // 解析文件内容进行预览
  if (file.raw) {
    parseImportFile(file.raw)
  }
}

// 解析导入文件
const parseImportFile = (file) => {
  const reader = new FileReader()
  
  reader.onload = (e) => {
    const content = e.target.result
    const fileName = file.name.toLowerCase()
    
    try {
      if (fileName.endsWith('.csv')) {
        // 解析CSV
        const lines = content.split('\n').filter(line => line.trim())
        const headers = lines[0].split(',')
        const data = []
        
        for (let i = 1; i < Math.min(lines.length, 6); i++) {
          const values = lines[i].split(',')
          data.push({
            account: values[0]?.trim(),
            name: values[1]?.trim(),
            email: values[2]?.trim(),
            major: values[3]?.trim(),
            className: values[4]?.trim()
          })
        }
        
        importPreviewData.value = data
      } else {
        // Excel文件需要使用xlsx库解析
        ElMessage.info('Excel文件预览功能开发中，请使用CSV格式')
      }
    } catch (error) {
      console.error('文件解析失败:', error)
      ElMessage.error('文件格式错误')
    }
  }
  
  if (file.name.toLowerCase().endsWith('.csv')) {
    reader.readAsText(file)
  } else {
    reader.readAsBinaryString(file)
  }
}

// 确认导入
const confirmImport = async () => {
  // 检查文件列表
  if (!fileList.value || fileList.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }
  
  // 获取原始文件对象
  const file = fileList.value[0].raw || fileList.value[0]
  if (!file) {
    ElMessage.warning('文件读取失败，请重新上传')
    return
  }
  
  try {
    importing.value = true
    const formData = new FormData()
    formData.append('file', file)
    
    const result = await batchImportStudents(formData)
    
    // 正确访问返回结果
    const data = result.data || result
    
    console.log('导入结果:', data)
    
    if (data.successCount > 0) {
      ElMessage.success(`导入完成：成功 ${data.successCount} 个，失败 ${data.failCount || 0} 个`)
    } else {
      ElMessage.warning(`导入失败：${data.failCount || 0} 个`)
    }
    
    // 显示失败详情
    if (data.failDetails && data.failDetails.length > 0) {
      console.log('失败详情:', data.failDetails)
    }
    
    // 关闭对话框
    importDialogVisible.value = false
    fileList.value = []
    importPreviewData.value = []
    
    // 重置分页到第一页，然后重新加载学生列表
    pagination.current = 1
    await loadStudents()
    
    console.log('导入后列表已刷新')
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error(error.message || '导入失败')
  } finally {
    importing.value = false
  }
}

// 导出学生数据
const exportStudents = async () => {
  try {
    ElMessage.info('正在导出学生数据...')
    const params = {
      page: pagination.current,
      size: pagination.size,
      keyword: searchKeyword.value
    }
    
    // 合并筛选条件
    Object.assign(params, filterForm.value)
    
    console.log('导出参数:', params)
    
    // 直接使用axios下载文件
    const response = await request({
      url: '/teacher/students/export',
      method: 'get',
      params,
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '学生数据导出.xlsx')
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error.message || error))
  }
}

// 计算天数差
const getDaysAgo = (date) => {
  if (!date) return 0
  const now = new Date()
  const target = new Date(date)
  return Math.floor((now - target) / (1000 * 60 * 60 * 24))
}

// 加载统计图表数据
const loadChartStatistics = async () => {
  try {
    // 获取综合统计数据
    const overviewResult = await getOverviewStatistics()
    
    // 获取趋势统计数据
    const trendResult = await getTrendStatistics({ period: 'day', days: 30 })
    
    // 获取活跃度分析数据
    const activityResult = await getStudentActivity()
    
    // 更新图表
    updateCharts(overviewResult, trendResult, activityResult)
  } catch (error) {
    console.error('加载统计图表数据失败:', error)
    ElMessage.error('加载统计图表数据失败')
  }
}

// 更新图表
const updateCharts = (overviewData, trendData, activityData) => {
  // 更新专业分布饼图
  updateMajorChart(overviewData.data || overviewData)
  
  // 更新班级提交统计柱状图
  updateClassChart(overviewData.data || overviewData)
  
  // 更新学生注册趋势折线图
  updateTrendChart(trendData.data || trendData)
  
  // 更新活跃度分析图
  updateActivityChart(activityData.data || activityData)
}

// 更新专业分布饼图
const updateMajorChart = (data) => {
  if (!majorChartRef.value || !data.majorDistribution) return
  
  const chart = echarts.init(majorChartRef.value)
  
  const option = {
    title: {
      text: '专业分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '专业分布',
        type: 'pie',
        radius: '50%',
        data: data.majorDistribution.map(item => ({
          name: item.major,
          value: item.studentCount
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 更新班级提交统计柱状图
const updateClassChart = (data) => {
  if (!classChartRef.value || !data.classDistribution) return
  
  const chart = echarts.init(classChartRef.value)
  
  const option = {
    title: {
      text: '班级提交统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: data.classDistribution.map(item => item.className)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '提交次数',
        type: 'bar',
        data: data.classDistribution.map(item => item.submissionCount),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 更新学生注册趋势折线图
const updateTrendChart = (data) => {
  if (!trendChartRef.value || !data.submissionTrends) return
  
  const chart = echarts.init(trendChartRef.value)
  
  // 确保数据格式正确
  const trends = Array.isArray(data.submissionTrends) ? data.submissionTrends : [];
  
  const option = {
    title: {
      text: '学生注册趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: trends.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '注册人数',
        type: 'line',
        data: trends.map(item => item.submissions || item.count || 0),
        smooth: true,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 更新活跃度分析图
const updateActivityChart = (data) => {
  if (!activityChartRef.value) return
  
  const chart = echarts.init(activityChartRef.value)
  
  // 使用真实的活跃度数据
  const activityData = [
    { name: '高活跃', value: data.activeStudents || data.high || 0 },
    { name: '中活跃', value: data.mediumStudents || data.medium || 0 },
    { name: '低活跃', value: data.inactiveStudents || data.low || 0 }
  ]
  
  const option = {
    title: {
      text: '活跃度分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '活跃度',
        type: 'pie',
        radius: ['40%', '70%'],
        data: activityData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化图表
const initCharts = () => {
  // 加载图表数据
  loadChartStatistics()
}

onMounted(() => {
  appStore.setPageTitle('学生管理')
  appStore.setBreadcrumbs([
    { title: '教师管理', path: '/teacher' },
    { title: '学生管理', path: '/teacher/students' }
  ])
  
  loadStudents()
  // 初始化图表
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.student-management {
  max-width: 100%; /* 改为100%充满容器 */
  margin: 0;
  padding: 0;
}

.page-header {
  margin-bottom: 16px; /* 减小间距 */
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 表格头部 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.table-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

/* 操作按钮组 */
.toolbar-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.toolbar-buttons .el-button {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 操作工具栏按钮只显示图标 */
.toolbar-buttons .el-button span {
  display: inline;
}

.toolbar-buttons .el-button .el-icon {
  margin-right: 5px;
}

.import-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.import-actions {
  display: flex;
  justify-content: flex-end;
}

.student-detail {
  padding: 20px;
}

.submission-stats,
.recent-submissions {
  margin-top: 24px;
}

.submission-stats h3,
.recent-submissions h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.import-preview {
  margin-top: 20px;
}

.import-preview h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.el-icon--upload {
  font-size: 67px;
  color: #C0C4CC;
  margin: 40px 0 16px;
  line-height: 50px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409EFF;
  font-style: normal;
}

/* 统计图表样式 */
.charts-section {
  margin-top: 24px;
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.chart-container {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 16px 0 0 0;
  font-size: 14px;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left {
    justify-content: center;
  }
  
  .table-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-right {
    display: flex;
    justify-content: center;
  }
  
  .toolbar-buttons {
    justify-content: center;
  }
}
</style>
